package cn.schoolwow.quickdao.test.module.business.user.dml.user.flow.compare;

import cn.schoolwow.quickdao.domain.DAO;
import cn.schoolwow.quickdao.domain.database.dml.CompareInstanceListResult;
import cn.schoolwow.quickdao.test.entity.User;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import org.junit.Assert;

import java.util.ArrayList;
import java.util.List;

public class SetAndCompareUserListFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        currentInstanceEmpty(flowContext);
        totalInstanceEmpty(flowContext);
        normalCompare(flowContext);
    }

    @Override
    public String name() {
        return "设置并比较用户列表";
    }

    private void currentInstanceEmpty(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);

        List<User> userTotalList = dao.query(User.class).execute().getList();
        CompareInstanceListResult<User> compareInstanceListResult = dao.uniqueFieldNames("username", "password")
                .compareInstanceList(null,userTotalList);
        Assert.assertEquals(userTotalList.size(), compareInstanceListResult.deleteInstanceList.size());
    }

    private void totalInstanceEmpty(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);

        List<User> compareUserList = new ArrayList<>();
        for(int i=20;i<=30;i++){
            User user = new User();
            user.setUsername("user"+i);
            user.setPassword("123456");
            user.setEmail("user"+i+"@fake.com");
            user.setMobile("12345678911");
            compareUserList.add(user);
        }
        CompareInstanceListResult<User> compareInstanceListResult = dao.uniqueFieldNames("username", "password")
                .compareInstanceList(compareUserList,new ArrayList<>());
        Assert.assertEquals(compareUserList.size(), compareInstanceListResult.insertInstanceList.size());
    }

    private void normalCompare(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);

        List<User> compareUserList = new ArrayList<>();
        for(int i=0;i<=20;i++){
            User user = new User();
            user.setUsername("user"+i);
            user.setPassword("123456");
            user.setEmail("user"+i+"@fake.com");
            user.setMobile("12345678911");
            compareUserList.add(user);
        }
        CompareInstanceListResult<User> compareInstanceListResult = dao.uniqueFieldNames("username", "password").compareInstanceList(compareUserList);

        Assert.assertEquals(10, compareInstanceListResult.insertInstanceList.size());
        Assert.assertEquals(11, compareInstanceListResult.updateInstanceList.size());
    }
}
